package com.ruoyi.controller;

import com.ruoyi.platform.annotation.Log;
import com.ruoyi.platform.core.controller.BaseController;
import com.ruoyi.platform.core.domain.AjaxResult;
import com.ruoyi.platform.core.domain.R;
import com.ruoyi.platform.core.page.TableDataInfo;
import com.ruoyi.platform.enums.BusinessType;
import com.ruoyi.platform.utils.poi.ExcelUtil;
import com.ruoyi.domain.FileUploadTask;
import com.ruoyi.dto.InitTaskParam;
import com.ruoyi.dto.Result;
import com.ruoyi.dto.TaskInfoDTO;
import com.ruoyi.service.IFileUploadTaskService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分片上传-分片任务记录Controller
 *
 * @author ruoyi
 * @date 2023-02-03
 */
@RestController
@RequestMapping("/admin/minioUploadTask")
@Api(tags = {"分片上传-分片任务记录服务"})
public class FileUploadTaskController extends BaseController {

    @Autowired
    private IFileUploadTaskService fileUploadTaskService;

    /**
     * 查询分片上传-分片任务记录列表
     */
    @PreAuthorize("@ss.hasPermi('admin:MinioUploadTask:list')")
    @GetMapping("/list")
    @ApiOperation(value = "查询分片上传-分片任务记录列表", httpMethod = "GET", notes = "查询分片上传-分片任务记录列表")
    public TableDataInfo list(FileUploadTask fileUploadTask) {
        startPage();
        List<FileUploadTask> list = fileUploadTaskService.selectFileUploadTaskList(fileUploadTask);
        return getDataTable(list);
    }

    /**
     * 导出分片上传-分片任务记录列表
     */
    @PreAuthorize("@ss.hasPermi('admin:MinioUploadTask:export')")
    @Log(title = "分片上传-分片任务记录", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ApiOperation(value = "导出分片上传-分片任务记录列表", httpMethod = "POST", notes = "导出分片上传-分片任务记录列表")
    public void export(HttpServletResponse response, FileUploadTask fileUploadTask) {
        List<FileUploadTask> list = fileUploadTaskService.selectFileUploadTaskList(fileUploadTask);
        ExcelUtil<FileUploadTask> util = new ExcelUtil<FileUploadTask>(FileUploadTask.class);
        util.exportExcel(response, list, "分片上传-分片任务记录数据");
    }

    /**
     * 获取分片上传-分片任务记录详细信息
     */
    @PreAuthorize("@ss.hasPermi('admin:MinioUploadTask:query')")
    @GetMapping(value = "/{id}")
    @ApiOperation(value = "获取分片上传-分片任务记录详细信息", httpMethod = "GET", notes = "获取分片上传-分片任务记录详细信息")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(fileUploadTaskService.selectFileUploadTaskById(id));
    }

    /**
     * 新增分片上传-分片任务记录
     */
    @PreAuthorize("@ss.hasPermi('admin:MinioUploadTask:add')")
    @Log(title = "分片上传-分片任务记录", businessType = BusinessType.INSERT)
    @PostMapping
    @ApiOperation(value = "新增分片上传-分片任务记录", httpMethod = "POST", notes = "新增分片上传-分片任务记录")
    public AjaxResult add(@RequestBody FileUploadTask fileUploadTask) {
        return toAjax(fileUploadTaskService.insertFileUploadTask(fileUploadTask));
    }

    /**
     * 修改分片上传-分片任务记录
     */
    @PreAuthorize("@ss.hasPermi('admin:MinioUploadTask:edit')")
    @Log(title = "分片上传-分片任务记录", businessType = BusinessType.UPDATE)
    @PutMapping
    @ApiOperation(value = "修改分片上传-分片任务记录", httpMethod = "PUT", notes = "修改分片上传-分片任务记录")
    public AjaxResult edit(@RequestBody FileUploadTask fileUploadTask) {
        return toAjax(fileUploadTaskService.updateFileUploadTask(fileUploadTask));
    }

    /**
     * 删除分片上传-分片任务记录
     */
    @PreAuthorize("@ss.hasPermi('admin:MinioUploadTask:remove')")
    @Log(title = "分片上传-分片任务记录", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    @ApiOperation(value = "删除分片上传-分片任务记录", httpMethod = "DELETE", notes = "删除分片上传-分片任务记录")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(fileUploadTaskService.deleteFileUploadTaskByIds(ids));
    }

    /**
     * 获取上传进度
     *
     * @param identifier 文件md5
     * @return
     */
    @GetMapping("/taskInfo/{identifier}")
    @Log(title = "获取上传进度", businessType = BusinessType.QUERY)
    public R<TaskInfoDTO> taskInfo(@PathVariable("identifier") String identifier) {
        return R.ok(fileUploadTaskService.getTaskInfo(identifier));
    }

    /**
     * 创建一个上传任务
     *
     * @return
     */
    @PostMapping("/initTask")
    @Log(title = "创建一个上传任务", businessType = BusinessType.INSERT)
    public R<TaskInfoDTO> initTask(@Valid @RequestBody InitTaskParam param, BindingResult bindingResult) {
        if (bindingResult.hasErrors()) {
            return R.fail(bindingResult.getFieldError().getDefaultMessage());
        }
        return R.ok(fileUploadTaskService.initTask(param));
    }


    /**
     * 获取每个分片的预签名上传地址
     *
     * @param identifier
     * @param partNumber
     * @return
     */
    @GetMapping("preSignUploadUrl/{identifier}/{partNumber}")
    @Log(title = "获取每个分片的预签名上传地址", businessType = BusinessType.QUERY)
    public Result preSignUploadUrl(@PathVariable("identifier") String identifier, @PathVariable("partNumber") Integer partNumber) {
        FileUploadTask task = fileUploadTaskService.getByIdentifier(identifier);
        if (task == null) {
            return Result.error("分片任务不存在");
        }
        Map<String, String> params = new HashMap<>();
        params.put("partNumber", partNumber.toString());
        params.put("uploadId", task.getUploadId());
        return Result.ok(fileUploadTaskService.genPreSignUploadUrl(task.getBucketName(), task.getObjectKey(), params));
    }

    /**
     * 合并分片
     *
     * @param identifier
     * @return
     */
    @PostMapping("/merge/{identifier}")
    @Log(title = "合并分片", businessType = BusinessType.OTHER)
    public R merge(@PathVariable("identifier") String identifier) {
        return R.ok(fileUploadTaskService.merge(identifier));
    }

    /**
     * 上传每个分片
     *
     * @param identifier
     * @param partNumber
     * @return
     */
    @ApiOperation(value = "上传每个分片")
    @PostMapping("/partUpload/{identifier}/{partNumber}")
    public Result partUpload(@PathVariable("identifier") String identifier, @PathVariable("partNumber") Integer partNumber,
                             HttpServletRequest request) throws Exception {
        FileUploadTask task = fileUploadTaskService.getByIdentifier(identifier);
        if (task == null) {
            return Result.error("分片任务不存在");
        }
        Boolean isEnd = false;
        Long partSize = task.getChunkSize();
        if (task.getChunkNum().compareTo(partNumber) == 0) {
            isEnd = true;
            partSize = task.getTotalSize() - partSize * (partNumber - 1);
        }
        InputStream inputStream = request.getInputStream();
        return Result.ok(fileUploadTaskService.partUpload(task.getBucketName(), task.getObjectKey(), task.getUploadId(), partNumber, inputStream, isEnd, partSize));
    }

}
